import java.awt.Color;
import java.util.concurrent.CyclicBarrier;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Balls {
	 static CyclicBarrierNew barrier = null;
	
    public static void nap(int ms) {
	try {
	    Thread.sleep(ms);
	}
	catch(InterruptedException e) {
	    //
	    //  Print out the name of the tread that caused this.
	    //
	    System.err.println("Thread "+Thread.currentThread().getName()+
			       " throwed exception "+e.getMessage());
	}
    }

    public static void main(String[] a) {
	
        final BallWorld world = new BallWorld();
        final JFrame win = new JFrame();
        SwingUtilities.invokeLater(new Runnable() {
		    public void run() {
				win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				win.getContentPane().add(world);
				win.pack();
				win.setVisible(true);
		    }});
	
        Thread.currentThread().setName("MyMainThread");
	
		//solution for ex 2.3
		//	barrier = new CyclicBarrier(4, new Runnable(){
		//		public void run(){
		//				System.out.println("Done.");
		//		}
		//	});
	
		//solution for ex 2.4
		barrier = new CyclicBarrierNew(4);
	
		nap((int)(5000*Math.random()));
		new Ball(barrier, world, 50, 80, 5, 10, Color.red).start();
		nap((int)(5000*Math.random()));
		new Ball(barrier, world, 70, 100, 8, 6, Color.blue).start();
		nap((int)(5000*Math.random()));
		new Ball(barrier, world, 150, 100, 9, 7, Color.green).start();
		nap((int)(5000*Math.random()));
		new Ball(barrier, world, 200, 130, 3, 8, Color.black).start();
		nap((int)(5000*Math.random()));
    }
}
